﻿using MugenInjection.Infrastructure;
using MugenInjection.Interface;
using MugenInjection.Xml.Components;
using MugenInjection.Xml.Interface.Components;

// ReSharper disable CheckNamespace
namespace MugenInjection
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Represents extensions for <see cref="IInjector"/>.
    /// </summary>
    public static class XmlInjectorExtensions
    {
        #region Methods

        /// <summary>
        /// Loads a series instances of <see cref="IBinding"/> from xml.
        /// </summary>
        /// <param name="injector">Specified <see cref="IInjector"/>.</param>
        /// <param name="xml">The specified xml for load bindings.</param>
        /// <param name="moduleName">The specified module name for load, default used from xml.</param>
        public static void LoadXmlModule(
#if !NET2
this
#endif
            IInjector injector, string xml, string moduleName = null)
        {
            Validate.ArgumentNotNull(injector, "injector");
            IXmlBindingLoaderComponent xmlBindingLoaderComponent = GetOrAddXmlComponent(injector);
            xmlBindingLoaderComponent.LoadBindings(xml, moduleName);
        }

        /// <summary>
        /// Unloads a bindings from the specified xml module.
        /// </summary>
        /// <param name="injector">Specified <see cref="IInjector"/>.</param>
        /// <param name="moduleName">The specified xml module.</param>
        public static void UnloadXmlModule(
#if !NET2
this
#endif
            IInjector injector, string moduleName)
        {
            Validate.ArgumentNotNullOrEmpty(moduleName, "moduleName");
            IXmlBindingLoaderComponent xmlBindingLoaderComponent = GetOrAddXmlComponent(injector);
            xmlBindingLoaderComponent.UnloadBindings(moduleName);
        }

        private static IXmlBindingLoaderComponent GetOrAddXmlComponent(IInjector injector)
        {
            IXmlBindingLoaderComponent xmlBindingLoader;
            if (injector.Components.TryGet(out xmlBindingLoader))
                return xmlBindingLoader;
            xmlBindingLoader = new XmlBindingLoaderComponent();
            injector.Components.Add(xmlBindingLoader);
            return xmlBindingLoader;
        }

        #endregion
    }
}